/*
 * @Author: HaiJun
 * @FilePath: \flutter_demo_show\lib\utils\http.dart
 * @Description: 
 * 
 */
import 'package:dio/dio.dart';
// import './CustomInterceptor.dart';

class HttpApi {
  // 配置基本的请求选项
  static final BaseOptions options = BaseOptions(
    baseUrl: 'http://jctt.net/yonghu', // 设置请求的基础 URL
    method: 'GET', //默认请求方法
    connectTimeout: const Duration(seconds: 5), // 设置连接超时时间为 5 秒
    receiveTimeout: const Duration(seconds: 3), // 设置接收超时时间为 3 秒
    headers: {
      'User-Agent': 'Dio', // 设置请求头信息
    },
  );
  static Dio dio = Dio(options);

  static Future<T> request<T>(String url,
      {String method = "get",
      Map<String, dynamic>? params,
      required FormData data}) async {
    // 1请求的单独配置
    final options = Options(method: method);
    // 2 添加一个拦截器
    Interceptor inter = InterceptorsWrapper(
      onRequest: (options, handler) {
        return handler.next(options);
      },
      onResponse: (e, handler) {
        print(e);
        return handler.next(e);
      },
      onError: (e, handler) {
        print(e);

        return handler.next(e);
      },
    );

    List<Interceptor> inters = [];
    // inters.add(CustomInterceptor()); //添加自定义拦截器
    // inters.add(LogInterceptor()); //添加内置拦截器

    dio.interceptors.addAll(inters);

    // 3 发起网络请求
    try {
      Response response =
          await dio.request<T>(url, queryParameters: params, options: options);
      print("测试");
      print(url);
      return response.data;
    } catch (e) {
      print(e);
      return Future.error(e);
    }
  }
}
